package com.zzw.thread;

/**
 * Created by Administrator on 2018/5/17.
 */
public class DeadLock2 extends Thread {

    protected Object tool;
    private static Object fork1 = new Object();
    private static Object fork2 = new Object();

    public DeadLock2(Object obj){
        this.tool = obj;
        if (tool == fork1){
            this.setName("哲学家A");
        }
        else {
            this.setName("哲学家B");
        }
    }

    @Override
    public void run() {
       if(tool == fork1){
           synchronized (fork1){
               try {
                   Thread.sleep(500);
               }
               catch(Exception e){
                   e.printStackTrace();
               }
               synchronized (fork2){
                   System.out.println("A");
               }
           }
       }
       else {
           synchronized (fork2){
               try {
                   Thread.sleep(500);
               }
               catch(Exception e){
                   e.printStackTrace();
               }
               synchronized (fork1){
                   System.out.println("B");
               }
           }
       }
    }

    public static void main(String[] args) throws InterruptedException {
        DeadLock2 lock1 = new DeadLock2(fork1);
        DeadLock2 lock2 = new DeadLock2(fork2);
        lock1.start();
        lock2.start();
        Thread.sleep(1000);
    }
}
